import { defineAsyncComponent } from 'vue';
const adminVisualComps = import.meta.glob('@/admin/visual/components/**/*.vue');
const visualComps = import.meta.glob('@/visual/components/**/*.vue');
import { useAdminVisualCompStore } from '@/admin/visual/js/visual-comp';
import { useVisualCompStore } from '@/visual/js/visual-comp';

export default function install(app) {
  const adminVisualComp = useAdminVisualCompStore();
  const visualComp = useVisualCompStore();

  Object.entries(adminVisualComps).forEach(async ([key, value]) => {
    const paths = key.replace('/src/admin/visual/components/', '').split('/');
    const name = getName('avc-', paths);
    app.component(name, defineAsyncComponent(value));
    adminVisualComp.setVisualComp(name, {name: name, styleList: []});
  });

  Object.entries(visualComps).forEach(async ([key, value]) => {
    const paths = key.replace('/src/visual/components/', '').split('/');
    const name = getName('vc-', paths);
    app.component(name, defineAsyncComponent(value));
    visualComp.setVisualComp(name, {name: name, styleList: []});
  });
}

function getName(prefix, paths) {
  let name = prefix + paths[0];
  if (paths[1] !== 'index.vue') {
    name += '-' + paths[1].replace('.vue', '');
  }
  if (paths.length>2 && paths[2] !== 'index.vue') {
    name += '-' + paths[2].replace('.vue', '');
  }
  if (paths.length>3 && paths[3] !== 'index.vue') {
    name += '-' + paths[3].replace('.vue', '');
  }
  name = name.replace(/[A-Z]/g, function(str) {
    return '-' + str.toLowerCase();
  });
  return name;
}